package ktor

import com.liftric.kvault.KVault
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.path
import ktor.models.ApiResponse
import models.AuthRequest
import sendRequest

class KtorAuthDataSource(
    private val httpClient: HttpClient,
    private val kVault: KVault
) {
    suspend fun login(username: String, password: String): Result<String?> {
        return sendRequest {
            httpClient.post {
                url {
                    path("/inventory/api/auth/login")
                }
                setBody(AuthRequest(username, password))
            }.body<ApiResponse<String>>().data.also {
                it?.let { token -> kVault.set("token", token) }
            }
        }
    }

    suspend fun register(username: String, password: String): Result<String?> {
        return sendRequest {
            httpClient.post {
                url {
                    path("/inventory/api/auth/register")
                }
                setBody(AuthRequest(username, password))
            }.body<ApiResponse<String>>().data.also {
                it?.let { token -> kVault.set("token", token) }
            }
        }
    }

    fun isTokenWritten(): Boolean {
        return kVault.string("token") != null
    }
}